//
//  TopicWaterFallLayout.m
//  miaopai
//
//  Created by duyifang on 15/11/14.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "TopicWaterFallLayout.h"

#define kWidth [UIScreen mainScreen].bounds.size.width

@implementation TopicWaterFallLayout

- (void)prepareLayout
{
    [super prepareLayout];
    self.maxHeight = 0;
    self.array = [NSMutableArray array];
    CGFloat leftY = 0;
    CGFloat rigthY = 0;
    CGFloat maxLeft = 0;
    CGFloat maxRight = 0;
    for (int j = 0; j < [self.collectionView numberOfSections]; j++) {
        NSInteger count = [self.collectionView numberOfItemsInSection:j];
        if(j == 1)
        {
            //第一列item y坐标的初始值
            leftY = kWidth * 1.5;
            
            //第二列item y坐标的初始值
            rigthY = kWidth * 1.5;
        }
        for (int i = 0; i < count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:j];
            UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            float offSetX = 0;
            
            if (j == 0) {
                offSetX = 0;
            }else if (j == 1 )
            {
                if (i % 2 == 0) {
                    //设置第一列 item x坐标
                    offSetX = 10;
                }else
                {
                    offSetX = 20 + (kWidth - 30) / 2;
                }
            }
            
            CGSize itemSize = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
            
            
            if (i % 2 == 0) {
                attributes.frame = CGRectMake(offSetX, leftY, itemSize.width, itemSize.height);
                maxLeft = leftY + itemSize.height;
                leftY += itemSize.height + 10;
            }else
            {
                offSetX = 20 + (kWidth - 30) / 2;
                attributes.frame = CGRectMake(offSetX, rigthY, itemSize.width, itemSize.height);
                maxRight = rigthY + itemSize.height;
                rigthY += itemSize.height + 10;
            }
            self.maxHeight = maxLeft > rigthY ? maxLeft + 10 : maxRight + 10;
            
            [self.array addObject:attributes];
            
        }
    }

}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < self.array.count; i++) {
        UICollectionViewLayoutAttributes *attriutes = [self.array objectAtIndex:i];
        if (CGRectIntersectsRect(rect, attriutes.frame)) {
            [array addObject:attriutes];
        }
    }
    return array;
}

- (CGSize)collectionViewContentSize
{
    return CGSizeMake(self.collectionView.frame.size.width, self.maxHeight);
}

@end